/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package plash.display;

import java.util.ArrayList;
import plash.geom.Point;
import plash.geom.Rectangle;
import processing.core.PGraphics;

/**
 *
 * @author  #0K Srinivasan <hashok.com>
 */
public class GraphicLinearPathShape implements IGraphicCommand, IGraphicShape
{
    protected ArrayList<Point> __points;
    protected Graphics __g;
    protected PGraphics __painter;
    protected Point __minPoint = new Point(99999999,99999999);
    protected Point __maxPoint = new Point(-99999999,-99999999);
    protected Rectangle __boundingBox = new Rectangle(0, 0, 0, 0);

    public GraphicLinearPathShape(Graphics g)
    {
        __g = g;
        __painter = g.getPainter();
        __init();
    }

    protected final void __init()
    {
        __points = new ArrayList<Point>();
    }

    public void addToPath(Point point)
    {
        __points.add(point);
        
        __minPoint.setX(Math.min(point.getX(), __minPoint.getX()));
        __minPoint.setY(Math.min(point.getY(), __minPoint.getX()));
        
        __maxPoint.setX(Math.max(point.getX(), __maxPoint.getX()));
        __maxPoint.setY(Math.max(point.getY(), __maxPoint.getX()));
        
        __boundingBox.setX(__minPoint.getX());
        __boundingBox.setY(__minPoint.getY());
        
        __boundingBox.setWidth(__maxPoint.getX() - __minPoint.getY());
        __boundingBox.setHeight(__maxPoint.getY() - __minPoint.getY());
    }

    public Point getPoint(int index)
    {
        if (index > (__points.size() - 1))
        {
            return __points.get(__points.size() - 1);
        }
        return __points.get(index);
    }

    public Point getLastPoint()
    {
        if (__points.size() < 1)
        {
            return new Point();
        }
        return __points.get(__points.size() - 1);
    }

    @Override
    public void execute()
    {
        if(__g == null)
        {
            return;
        }
        if(__g.getOwner().getPainter() == null)
        {
            return;
        }
        
        if(__points.size() < 1)
        {
            return;
        }

        __g.getOwner().getPainter().beginShape();
        for (Point p : __points)
        {
            __g.getOwner().getPainter().vertex(p.getX(), p.getY());
        }
        __g.getOwner().getPainter().endShape();
    }

    @Override
    public Rectangle boundingBox()
    {
        return __boundingBox;
    }
}
